package com.clouddot.baipai.ui.util.cameraView;

import android.app.Activity;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 王士源 on 2017/10/30.
 */

public class CameraView extends SurfaceView implements SurfaceHolder.Callback, Camera.PictureCallback {
    private SurfaceHolder holder;
    private Camera camera;
    private boolean af;
    private boolean isUse = false;

    private Activity activity;

    public CameraView(Activity context) {//构造函数
        super(context);
//        Toast.makeText(context, "拍照中..." , Toast.LENGTH_SHORT).show();
        this.activity = context;

        holder = getHolder();//生成Surface Holder  
        holder.addCallback(this);

        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//指定Push Buffer
    }
    public  void closeCamera() {
        try {
            camera.stopPreview();
            camera.release();
            camera = null;
        } catch (Exception e) {
        }

    }
    public void surfaceCreated(SurfaceHolder holder) {//Surface生成事件的处理  
        try {

            //closeCamera();
            camera = Camera.open();
            Camera.Parameters p = camera.getParameters();
            p.setPictureSize(1500, 2000); //设置照片分辨率，太大上传不了
            camera.setParameters(p);

            camera.setPreviewDisplay(holder);
            //camera.setDisplayOrientation(90);  
        } catch (Exception e) {
        }
    }

    private void data2file(byte[] w, String fileName) throws Exception {//将二进制数据转换为文件的函数
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(fileName);
            out.write(w);
            out.close();
        } catch (Exception e) {
            if (out != null)
                out.close();
            throw e;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {//Surface改变事件的处理
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(width, height);
//        camera.setParameters(parameters);//设置参数

        camera.startPreview();//开始预览
        new MyThread().start();//这个线程实现拍照保存上传
        //camera.autoFocus(null);  
        // camera.takePicture(null, null, this);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

    }

    class MyThread extends Thread implements Camera.PictureCallback {
        @Override
        public void run() {
            super.run();
            camera.autoFocus(null);
            camera.takePicture(null, null, this);
//            while (true) {
//                System.out.println("拍照线程wu异常");
//                try {
//                    sleep(50000);//20秒执行一次
//                } catch (InterruptedException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }

        }

        /**
         * 发送文件post请求
         *
         * @return
         * @throws IOException
         */
        public String doFilePost(String urlstr, Map<String, String> map,
                                 Map<String, File> files) throws IOException {
            String BOUNDARY = "----WebKitFormBoundaryDwvXSRMl0TBsL6kW"; // 定义数据分隔线

            URL url = new URL(urlstr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Android WYJ");
            connection.setRequestProperty("Charsert", "UTF-8");
            connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(connection.getOutputStream());
            byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线

            // 文件
            if (files != null && !files.isEmpty()) {
                for (Map.Entry<String, File> entry : files.entrySet()) {
                    File file = entry.getValue();
                    String fileName = entry.getKey();

                    StringBuilder sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data;name=\"" + fileName
                            + "\";filename=\"" + file.getName() + "\"\r\n");
                    sb.append("Content-Type: image/jpg\r\n\r\n");
                    byte[] data = sb.toString().getBytes();
                    out.write(data);

                    DataInputStream in = new DataInputStream(new FileInputStream(
                            file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    out.write("\r\n".getBytes()); // 多个文件时，二个文件之间加入这个
                    in.close();
                }
            }
            // 数据参数
            if (map != null && !map.isEmpty()) {

                for (Map.Entry<String, String> entry : map.entrySet()) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\""
                            + entry.getKey() + "\"");
                    sb.append("\r\n");
                    sb.append("\r\n");
                    sb.append(entry.getValue());
                    sb.append("\r\n");
                    byte[] data = sb.toString().getBytes();
                    out.write(data);
                }
            }
            out.write(end_data);
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
//      BufferedReader reader = new BufferedReader(new InputStreamReader(
//              connection.getInputStream()));
//      String line = null;
//      while ((line = reader.readLine()) != null) {
//          System.out.println(line);
//      }

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inStream = connection.getInputStream();
                byte[] number = read(inStream);
                String json = new String(number);
                return json;
            }

            return null;
        }


        /**
         * 读取输入流数据 InputStream
         *
         * @param inStream
         * @return
         * @throws IOException
         */
        public  byte[] read(InputStream inStream) throws IOException {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            inStream.close();
            return outStream.toByteArray();
        }

        @Override
        public void onPictureTaken(byte[] data, Camera cameras) {
            // TODO Auto-generated method stub

            try {
                String path = android.os.Environment.getExternalStorageDirectory() + "/test.jpg";
                Log.v("path", path);
                data2file(data, path);    //到这步为止完成了自动拍照并保存，下面这个线程是上传的 想要触摸拍照的话要改写下的onTouchEvent方法，我这不用

                new Thread() {
                    @Override
                    public void run() {
                        Map<String, String> params = new HashMap<String, String>();
                        Map<String, File> files = new HashMap<String, File>();

                        try {
                            params.put("folder","cardsigner");
                            files.put("Filedata",new File(android.os.Environment.getExternalStorageDirectory() + "/test.jpg"));

                            String fileinfo = doFilePost("http://" +  Env.getAppContext().host+"/YDS/UploadFile", params, files);

                            activity.getIntent().putExtra("back", fileinfo);
                            activity.setResult(123, activity.getIntent());
                            closeCamera();
                            activity.finish();
                        }
                        catch (Exception ex){
                            Env.error(Environment.getInstance().fileUtil.Errorinfo(ex));

                            return;
                        }


                    }

                }.start();

            } catch (Exception e) {
                e.printStackTrace();
                Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

                activity.finish();
            }
            //camera.startPreview();
        }
    }
}
